<?php
include_once "header.php";
include_once "../date_utils.php";

$alert = $_GET["alert"];
$look = $_GET["look"];
$id_user = $_SESSION["data"]["id"];

if( !User::isAutentified() ) { 
  header('Location:../login.php?page=admin');
  exit();
} 

$place_id = htmlspecialchars($_GET['place_id']);

if(User::isAdmin()) {
  // hide marker on map
  if($task == "hide") {
    mysql_query("UPDATE places SET approved=0 WHERE id='$place_id'") or die(mysql_error());
    header("Location: index.php?view=$view&search=$search&p=$p");
    exit;
  }
  
  // show marker on map
  if($task == "approve") {
    mysql_query("UPDATE places SET approved=1 WHERE id='$place_id'") or die(mysql_error());
    header("Location: index.php?view=$view&search=$search&p=$p");
    exit;
  }
}
// completely delete marker from map
if($task == "delete") {
	
  //Checkear propietario o Admin
	$place_query = mysql_query("SELECT * FROM places WHERE id='$place_id' LIMIT 1");
	if(mysql_num_rows($place_query) != 1) { exit; }
	$place = mysql_fetch_assoc($place_query);
	
	if(!User::isAdmin() && ($place[id_user] != User::id())) {
		header('Location: index.php?alert=Esta protesta no te pertenece');
		exit();	
	}
	
	//Delete
  mysql_query("DELETE FROM places WHERE id='$place_id'") or die(mysql_error());
  header("Location: index.php?view=$view&search=$search&p=$p");
  exit;
}

// paginate
$items_per_page = 15;
$page_start = ($p-1) * $items_per_page;
$page_end = $page_start + $items_per_page;

// filter by approved
if($view == "approved") {
  $approved_filter = " AND approved='1'";
  $total = $total_approved;
} else if($view == "rejected") {
  $approved_filter = " AND approved='0'";
  $total = $total_rejected;
} else if($view == "pending") {
  $approved_filter = " AND approved='2'";
  $total = $total_pending;
} else if($view == "") {
  $approved_filter = "";
  $total = $total_all;
}

//filter by id_user
if(!User::isAdmin()) {
  $id_user_filter = " AND id_user='".User::id()."'";
}

if($search != "") {
  $places = mysql_query("SELECT * FROM places WHERE title LIKE '%$search%' $id_user_filter ORDER BY id DESC LIMIT $page_start, $items_per_page");
  $total = mysql_num_rows(mysql_query("SELECT id FROM places WHERE title LIKE '%$search%'")); 
}else{
  $places = mysql_query("SELECT * FROM places WHERE 1 $approved_filter $id_user_filter ORDER BY id DESC LIMIT $page_start, $items_per_page");
}

echo $admin_head;
?>

<script type="text/javascript" src="../scripts/bootbox.min.js"></script>

<?php
//$images = mysql_query("SELECT files.id_file as file_id FROM files, places WHERE places.id_user ='$id_user' AND files.place_id = places.id AND files.approved = '2' ");
$total_images_pending = 0;//mysql_num_rows($images);
?>
<div class="row-fluid">

<?php
if(User::isAdmin()) {
?>
<div class="span3">
	<div class="well" style="padding: 8px 0;">
		<ul class="nav nav-list">
			<li class="nav-header">Admin Menu</li>
			<li <?php if($look=="")echo "class=\"active\"";?>><a href="index.php"><i class="icon-home"></i> Protestas <?php if($total_pending>0){ echo "<span class=\"badge badge-info\">".$total_pending."</span>";}?></a></li>
			<? if ( User::isAdmin() ){ ?> <li <?php if($look=="registered_users")echo "class=\"active\"";?>><a href="index.php?look=registered_users"><i class="icon-user"></i> Usuarios</a></li> <? } ?>
			<li><a href="#"><i class="icon-picture"></i> Imágenes<?php if($total_images_pending>0){ echo "<span class=\"badge badge-info\">".$total_images_pending."</span>";}?></a></li>
			<li><a href="#"><i class="icon-comment"></i> Comentarios</a></li>
			<li class="divider"></li>
			<li><a href="#"><i class="icon-asterisk"></i> Opciones</a></li>
			<li><a href="../index.php"><i class="icon-share"></i> Volver al mapa</a></li>
			<li><a href="../index.php?task=logout"><i class="icon-off"></i> Salir</a></li>
		</ul>
	</div>
</div>

<div class="span9" id="admin">
<?
}else{
?>  
<div class="span12" id="admin">
<? 
}
   if($alert != "") {
      echo "
      <div class='alert alert-danger'>$alert</div>
      ";
    }
?>  

  <h3>
    <? if($total > $items_per_page) { ?>
      <?=$page_start+1?>-<? if($page_end > $total) { echo $total; } else { echo $page_end; } ?>
      de <?=$total?> protestas
    <? } else { ?>
      <?=$total?> protestas
    <? } ?>
  </h3>
  <ul class="list">
  <? if($look == "registered_users" && User::isAdmin()) {
     
    	$registered_users = mysql_query("SELECT * FROM users ORDER BY id DESC");
      while($registered_user = mysql_fetch_assoc($registered_users)) {
        echo " 
          <li>
            <div class='options'>
              <!-- <a class='btn btn-small btn-danger delete' data-id='$place[id]' href='#'>Borrar</a> -->
            </div>
            <div class='place_info'>
              <a href='mailto:$registered_user[email]' target='_blank'>
                $registered_user[email]
              </a>
              <span>$registered_user[nombre]</span> <span> | $registered_user[organizacion]</span> 
            </div>
          </li>
        ";       
       } ?>
   </ul>
 	<? } else { 
    	$today = date("Y-m-d");
      while($place = mysql_fetch_assoc($places)) {
        $place[uri] = str_replace("http://", "", $place[uri]);
        $place[uri] = str_replace("https://", "", $place[uri]);
        $place[uri] = str_replace("www.", "", $place[uri]);
        $place[finished] =  $place[end_date] < $today;
        $place[start_date] = convertDateToUserFormat($place[start_date]);
        $place[end_date] = convertDateToUserFormat($place[end_date]);
        $place[read_start_date] = toReadableDate($place[start_date],($place[start_date] == $place[end_date]));
        $place[read_end_date] = toReadableDate($place[end_date],true);
        if($place['start_date'] != $place['end_date']){
            $fechas = $place['read_start_date']." - ".$place['read_end_date'];
        }else{
           $fechas = $place['read_start_date'];
        }
        
        if(User::isAdmin()) {
        echo "
          <li class='bullet-".$place[type]."'>
            <div class='btn-group options'>
              <a class='btn btn-primary' data-toggle='tooltip' title='Editar' href='edit.php?place_id=$place[id]&view=$view&search=$search&p=$p'>
                <i class='icon-pencil icon-white'></i>
              </a>
              <a class='btn btn-primary' data-toggle='tooltip' title='Ver en mapa' href='../index.php?place_id=$place[id]'>
                <i class='icon-map-marker icon-white'></i>
              </a>
              <a class='btn ".(($place[approved] == 1)?"disabled":"btn-success")."' data-toggle='tooltip' title='Aprobar'".(($place[approved] != 1)?" href='index.php?task=approve&place_id=$place[id]&view=$view&search=$search&p=$p'":"").">
                <i class='icon-ok icon-white'></i>
              </a>        
              <a class='btn ".(($place[approved] == 0)?"disabled":"btn-warning")."' data-toggle='tooltip' title='Ocultar'".(($place[approved] != 0)?" href='index.php?task=hide&place_id=$place[id]&view=$view&search=$search&p=$p'":"").">
                <i class='icon-remove icon-white'></i>
              </a>
              <a class='btn btn-danger delete' data-toggle='tooltip' title='Borrar' data-id='$place[id]' href='#'>
                <i class='icon-trash icon-white'></i>
              </a>
              <!--<a class='btn btn-inverse' data-toggle='tooltip' title='Ver emails' href='#'>
                <i class='icon-envelope icon-white'></i>
              </a>-->
            </div>
            <div class='place-info'>
              <div class='title' title='".$place[title]."'>".$place[title]."</div>
              <div class='date'>". $fechas . (($place['finished'])?" <span class='label label-important label-small'>Finalizada</span>":"").(($place[uri])?"<a target='_blank' href='http://$place[uri]' data-toggle='tooltip' title='http://$place[uri]'><i class='icon-globe'></i></a>":"")."</div>
            </div>   
          </li>
        ";
      } else{     
		    echo "
          <li class='bullet-".$place[type]."'>
            <div class='btn-group options'>
              <a class='btn btn-primary' data-toggle='tooltip' title='Editar' href='edit.php?place_id=$place[id]&view=$view&search=$search&p=$p'>
                <i class='icon-pencil icon-white'></i>
              </a>
              <a class='btn btn-primary' data-toggle='tooltip' title='Ver en mapa' href='../index.php?place_id=$place[id]'>
                <i class='icon-map-marker icon-white'></i>
              </a>
              <a class='btn btn-danger delete' data-toggle='tooltip' title='Borrar' data-id='$place[id]' href='#'>
                <i class='icon-trash icon-white'></i>
              </a>
            </div>
            <div class='place-info'>
              <div class='title' title='".$place[title]."'>".$place[title]."</div>
              <div class='date'>". $fechas . (($place['finished'])?" <span class='label label-important label-small'>Finalizada</span>":"").(($place[uri])?"<a target='_blank' href='http://$place[uri]' data-toggle='tooltip' title='http://$place[uri]'><i class='icon-globe'></i></a>":"")."</div>
            </div>   
          </li>
        ";        
        }
      }
      ?>
   </ul>
<script>
   $(document).ready(function(){
    $("[data-toggle='tooltip']").tooltip({    
      'selector': '',
      'placement': 'bottom'
    });
   });
</script>  
  <? if($p > 1 || $total >= $items_per_page) { ?>
    <ul class="pager">
      <? if($p > 1) { ?>
        <li class="previous">
          <a href="index.php?view=<?=$view?>&search=<?=$search?>&p=<? echo $p-1; ?>">&larr; Anterior</a>
        </li>
      <? } ?>
      <? if($total >= $items_per_page * $p) { ?>
        <li class="next">
          <a href="index.php?view=<?=$view?>&search=<?=$search?>&p=<? echo $p+1; ?>">Siguiente &rarr;</a>
        </li>
      <? } ?>
    </ul>
  <? } 
    }
    ?>
  

</div>

</div>

    <? echo renderUserVoice(); ?>
    
    <script>
    	
    	$("#admin .delete").click(function(e) {
				e.preventDefault();
				var id = $(this).data('id');
				
				bootbox.setLocale('es');	
				bootbox.confirm("¿Estas seguro que eliminar esta protesta?", function(result) {
					if(result) window.location.href="index.php?task=delete&place_id="+id+"&view=<?=$view?>&search=<?=$search?>&p=<?=$p?>";
				}); 
			}); 
			

    </script>


<? echo $admin_foot ?>